package com.woniu.inlet.timer;

import com.woniu.adapter.DailyCodeValuationAdapter;
import com.woniu.adapter.GoldFundSellAdapter;
import com.woniu.adapter.SellRateAdapter;
import com.woniu.adapter.UserDetailAdapter;
import com.woniu.inlet.vo.ConfirmSellOrder;
import com.woniu.outlet.client.OrderMessage;
import com.woniu.outlet.client.UpdateOrderStatus;
import com.woniu.outlet.mysql.po.DailyCodeTOne;
import com.woniu.outlet.mysql.po.SellRateMySQL;
import com.woniu.outlet.redis.DailyCodeValuationRedisDao;
import com.woniu.service.bean.AddEarnings;
import com.woniu.service.bean.AddSellRecord;
import com.woniu.service.bean.GoldFundSell;
import com.woniu.service.domain.UserDetail;
import com.woniu.util.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class GoldFundSellOrderTimer {

    @Autowired
    private GoldFundSellAdapter goldFundSellAdapter;
    @Autowired
    private SellRateAdapter sellRateAdapter;
    @Autowired
    private DailyCodeValuationRedisDao dailyCodeValuationRedisDao;
    @Autowired
    private UpdateOrderStatus updateOrderStatus;
    @Autowired
    private UserDetailAdapter userDetailAdapter;
    @Autowired
    private OrderMessage orderMessage;
    @Autowired
    private DailyCodeValuationAdapter dailyCodeValuationAdapter;

    @Scheduled(cron = "0 30 23 ? * *") //每天十一点半对比数据
    public void goldFundSell() {
        //去重查询出sid
        Set<Integer> sIds = goldFundSellAdapter.getSIds();
        for (Integer sId : sIds) {
            //需要的数据
            BigDecimal sellShare = new BigDecimal(0); //份额
            BigDecimal sellCost = new BigDecimal(0); //手续费
            BigDecimal sellMoney = new BigDecimal(0); //总金额
            BigDecimal sellAmount = new BigDecimal(0); //扣除手续费之后的金额
            BigDecimal userPrice = new BigDecimal(0); //用户本金
            Integer userId = 0; //用户id
            String proType = ""; //产品类型
            int day = 0; //持有天数
            String code = "";
            //根据sid查询卖出的订单信息
            List<GoldFundSell> goldFundSellBySId = goldFundSellAdapter.getGoldFundSellBySId(sId);
            for (GoldFundSell goldFundSell : goldFundSellBySId) {
                if (goldFundSell.getSellTime().equals(AppUtils.getTimeg())) {
                    //用户本金
                    userPrice = userPrice.add(goldFundSell.getDealPrice());
                    //userid
                    userId = goldFundSell.getUserId();
                    //产品类型
                    proType = goldFundSell.getProductType();
                    //产品codeid
                    code = goldFundSell.getCodeId();
                    //计算当前产品的持有时间，用来查出产品的手续费利率
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse1 = format.parse(goldFundSell.getSellTime());
                        Date parse2 = format.parse(goldFundSell.getSchedule());
                        //得到产品持有天数
                        day = (int) ((parse1.getTime() - parse2.getTime()) / (1000 * 3600 * 24));
                        SellRateMySQL sellRateByDay = sellRateAdapter.getSellRateByDay(day);
                        log.debug("利率为：{}", sellRateByDay.getRate());
                        //累计份额
                        sellShare = sellShare.add(goldFundSell.getSellSale());
                        //计算手续费
                        //从redis里面拿出数据
                        DailyCodeTOne dailyCodeTOne = dailyCodeValuationRedisDao.findById(goldFundSell.getCodeId()).orElseThrow(NullPointerException::new);
                        log.debug("从redis里面拿到的数据为：{}", dailyCodeTOne);
                        //交易总金额=当日估值x份额
                        BigDecimal multiply = goldFundSell.getSellSale().multiply(dailyCodeTOne.getTodayValuation());
                        sellMoney = sellMoney.add(multiply);
                        //手续费
                        BigDecimal cost = multiply.multiply(BigDecimal.valueOf(sellRateByDay.getRate()).divide(new BigDecimal(100)));
                        //累计手续费
                        sellCost = sellCost.add(cost);
                        BigDecimal amount = multiply.subtract(cost);
                        sellAmount = sellAmount.add(amount);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            //openfeign将数据发给订单模块
            ConfirmSellOrder confirmSellOrder = new ConfirmSellOrder();
            confirmSellOrder.setId(sId);
            confirmSellOrder.setSellShare(sellShare.divide(new BigDecimal("1"), 4, BigDecimal.ROUND_DOWN).toString());
            confirmSellOrder.setHoldDay(String.valueOf(day));
            confirmSellOrder.setSellCost(sellCost.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            confirmSellOrder.setSellAmount(sellAmount.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            updateOrderStatus.confirmSellOrder(confirmSellOrder);
            //向平台收益表添加数据
            AddEarnings addEarnings = new AddEarnings();
            addEarnings.setUserId(userId);
            addEarnings.setDealPrice(sellMoney.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            addEarnings.setDealCharge(sellCost.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            addEarnings.setDealTime(AppUtils.getNowTimeStr());
            addEarnings.setDealType(AddEarnings.SELL);
            addEarnings.setProductType(proType);
            addEarnings.execute();
            //向用户卖出记录表添加数据
            AddSellRecord addSellRecord = new AddSellRecord();
            addSellRecord.setUserId(userId);
            addSellRecord.setDealTime(AppUtils.getNowTimeStr());
            addSellRecord.setDealPrice(sellMoney.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            addSellRecord.setUserIncome((sellAmount.subtract(userPrice)).divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            addSellRecord.setDealCharge(sellCost.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            addSellRecord.setProductType(proType);
            addSellRecord.execute();
            //用户帐户更新
            UserDetail user = userDetailAdapter.getUserById(userId);
            UserDetail userDetail = new UserDetail();
            userDetail.setTotalAmount((user.getTotalAmount().add(sellAmount.subtract(userPrice))).divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            userDetail.setRestAmount((user.getRestAmount().add(sellAmount.subtract(userPrice)).add(userPrice)).divide(new BigDecimal("1"), 2, BigDecimal.ROUND_DOWN));
            userDetail.setUserId(user.getUserId());
            userDetailAdapter.updateInfo(userDetail);
            //给用户发送通知
            //从redis中通过codeid获取数据
            //获取基金的名字
            DailyCodeTOne dailyCodeValuationMySQL = dailyCodeValuationAdapter.getDailyCodeValuationMySQL(code);
            String inform = "您好，您有一笔订单:["+dailyCodeValuationMySQL.getName()+"]成功卖出,请注意验收。"+userId+"y";
            orderMessage.sendMessage("pay.inform.user", "pay_inform_user", inform);
        }
    }
}
